<?php
/************************************************************************
 Omnitrix - PHP Development Framework
 Copyright (C) 2012-2018 amonest(eastson@outlook.com)

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
************************************************************************/

function otx_error_handler($errno, $errstr, $errfile, $errline)
{
	switch ($errno) {
		case E_ERROR:
		case E_USER_ERROR:
			$message = "[$errno] $errstr ($errfile - $errline)";
			$priority = 'ERROR';
			break;

		case E_WARNING:
		case E_USER_WARNING:
			$message = "[$errno] $errstr ($errfile - $errline)";
			$priority = 'WARNING';
			break;

		default:
			$message = "[$errno] $errstr ($errfile - $errline)";
			$priority = 'NOTICE';
			break;
	}

	echo $message;
	otx_write_log($message, $priority);
	exit;
}

function otx_exception_handler($exception)
{
	echo $exception;
	otx_write_log($message, 'EXCEPTION');
	exit;
}

function otx_write_log($message, $priority = 'INFO')
{
	$output = '[' . date('c') . ']'
			. ' [' . $priority . ']'
					. ' ' . str_replace(array("\r\n", "\n"), PHP_EOL, $message)
					. PHP_EOL;

	$file = DIR_LOGS . date('Ymd') . '.log';

	$fp = fopen($file, 'a');
	fwrite($fp, $output);
	fclose($fp);
}

function otx_file_size($path)
{
	$size = 0;

	if (is_file($path)) {
		@$dh = opendir($path);

	    while ($name = @readdir($dh)) {
	    	if ($name != '.' && $name != '..') {
	    		$child = $path . '/' . $name;
	    		if (is_dir($child)) {
	    			$size += otx_file_size($child);
	    		} else {
	    			$size += filesize($child);
	    		}
	    	}
	    }

	    @closedir($dh);
	} else if (is_file($path)) {
		$size = filesize($path);
	}

    return $size;
}